<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :showMore="showMore"
      :rightBtnArr="rightBtnArr"
      :moreBtnArr="moreBtnArr"
      :creatInfo="creatInfo"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title">{{ basicFormData.type$ }}(样票)</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span>{{ title }}</span>
          <el-link
            v-if="showBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            maxlength="64"
            v-model="title"
            @blur="loseFocus"
            show-word-limit
            placeholder="请输入标题"
            clearable
            ref="mark"
            ><template slot="prepend" style="color: red"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item class="basic" name="0">
          <template slot="title"> 基本信息 </template>
          <editForm
            class="info-data"
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="basicFormData"
          ></editForm>
          <div
            class="table-content info-data"
            v-if="
              ticketType == 'ElectricalFirst' ||
              ticketType == 'ElectricalSecond' ||
              ticketType == 'PowerLineFirst'
            "
          >
            <el-row>
              <el-col :span="4"
                ><div class="itemTitle">工作要求的安全措施</div></el-col
              >
              <el-col
                :span="20"
                v-if="
                  ticketType == 'ElectricalFirst' ||
                  ticketType == 'ElectricalSecond'
                "
                ><div class="safe-info">
                  <div class="safe-data">
                    <el-form :model="safeDetails" :rules="rules" ref="form">
                      <el-table border :data="safeDetails.data" ref="table">
                        <el-table-column type="index" label="序号" width="50">
                        </el-table-column>
                        <el-table-column
                          class="item"
                          property="item"
                          label="安全措施项"
                        >
                          <template slot-scope="scope">
                            <span
                              v-show="scope.row.requiredFlag"
                              style="color: red"
                              >*
                            </span>
                            <span>{{ scope.row.item }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          class="value"
                          property="value"
                          label="对象"
                        >
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'data.' + scope.$index + '.value'"
                              :rules="
                                scope.row.requiredFlag == 1 ? rules.value : null
                              "
                            >
                              <el-input
                                size="mini"
                                class="value-input"
                                type="textarea"
                                :autosize="true"
                                v-if="isEditInfo"
                                v-model="scope.row.value"
                                placeholder="请输入"
                                maxlength="1024"
                                show-word-limit
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-form>
                  </div></div
              ></el-col>
              <el-col :span="20" v-if="ticketType == 'PowerLineFirst'"
                ><div class="safe-info">
                  <el-button
                    icon="el-icon-plus"
                    class="btn-text-blue add-btn"
                    size="mini"
                    @click="addSafeItem"
                    >新建</el-button
                  >
                  <div class="safe-data">
                    <el-form :model="safeDetails" :rules="rules" ref="form">
                      <el-table
                        border
                        :data="safeDetails.data"
                        :span-method="arraySpanMethod"
                        ref="table"
                      >
                        <el-table-column
                          class="type"
                          property="type"
                          label="站名"
                        >
                          <template slot-scope="scope">
                            <el-form-item>
                              <el-input
                                size="mini"
                                type="textarea"
                                :autosize="true"
                                v-if="isEditInfo"
                                v-model="scope.row.type"
                                placeholder="请输入"
                                maxlength="36"
                                show-word-limit
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          class="item"
                          property="item"
                          label="安全措施分类"
                        >
                          <template slot-scope="scope">
                            <span
                              v-show="scope.row.requiredFlag"
                              style="color: red"
                              >*
                            </span>
                            <span>{{ scope.row.item }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          class="value"
                          property="value"
                          label="安全措施描述"
                        >
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'data.' + scope.$index + '.value'"
                              :rules="
                                scope.row.requiredFlag == 1 ? rules.value : null
                              "
                            >
                              <el-input
                                size="mini"
                                class="value-input"
                                type="textarea"
                                :autosize="true"
                                v-if="isEditInfo"
                                v-model="scope.row.value"
                                placeholder="请输入"
                                maxlength="1024"
                                show-word-limit
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100">
                          <template slot-scope="scope">
                            <el-button
                              @click="deleteSafeItem(scope.row)"
                              type="text"
                              size="small"
                              >删除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-form>
                  </div>
                </div></el-col
              >
            </el-row>
          </div>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
  </div>
</template>
<script>
import { queryList } from "@/api/businessConfigurationManagement/securityMeasuresConfiguration.js";
import {
  getWorkTicketInfo,
  saveSampleTicket,
  deleteSampleTicket,
  getSampleTicketData,
} from "@/api/twoTicketManagement/workTicket.js";
export default {
  data() {
    return {
      isEditInfo: false,
      showMore: false,
      pageType: "", // 页面类型
      showInput: false, // 标题输入框
      title: "", // 标题内容
      showBtn: true, // 标题编辑按钮
      creatInfo: {}, // 右下角创建信息
      ticketType: "", // 工作票类型英文
      activeNames: ["0"],
      merge: 0,
      safeConfig: [], // 安全措施基础数据
      safeDetails: { data: [] }, // 安全措施
      rules: {
        value: [{ required: true, message: "请输入对象", trigger: "blur" }],
      },
      // 基本信息表单
      basicConfig: {
        labelWidth: "210px",
        itemArr: [
          {
            label: "工作票类型",
            prop: "type$",
            type: "text",
            span: 12,
            trigger: "change",
            required: true,
            disabled: true,
          },
          {
            label: "工作内容",
            prop: "content",
            type: "textarea",
            autosize: true,
            span: 24,
            maxlength: 3000,
            trigger: "change",
            required: true,
            isHide: true,
            placeholder: "请输入",
            methods: (res) => {
              if (!this.title) {
                if (res.length > 64) {
                  this.title = res.substring(0, 64);
                } else {
                  this.title = res;
                }
              }
            },
          },
          {
            label: "安全措施（注意事项）",
            prop: "safetyMeasures",
            type: "textarea",
            span: 24,
            autosize: true,
            maxlength: 3000,
            trigger: "change",
            isHide: true,
            placeholder: "请输入",
          },
          {
            label: "工作要求的安全措施",
            prop: "safetyMeasures",
            type: "textarea",
            span: 24,
            autosize: true,
            maxlength: 3000,
            trigger: "change",
            isHide: true,
            placeholder: "请输入",
          },
          {
            label: "工作任务",
            prop: "content",
            type: "textarea",
            span: 24,
            maxlength: 3000,
            autosize: true,
            trigger: "change",
            required: true,
            isHide: true,
            placeholder: "请输入",
            methods: (res) => {
              if (!this.title) {
                if (res.length > 64) {
                  this.title = res.substring(0, 64);
                } else {
                  this.title = res;
                }
              }
            },
          },
          {
            label: "执行本工作应采取的安全措施",
            prop: "safetyMeasures",
            type: "textarea",
            span: 24,
            autosize: true,
            maxlength: 3000,
            trigger: "change",
            isHide: true,
            placeholder: "请输入",
          },
          {
            label: "动火工作内容",
            prop: "content",
            type: "textarea",
            span: 24,
            maxlength: 3000,
            autosize: true,
            trigger: "change",
            required: true,
            isHide: true,
            placeholder: "请输入",
            methods: (res) => {
              if (!this.title) {
                if (res.length > 64) {
                  this.title = res.substring(0, 64);
                } else {
                  this.title = res;
                }
              }
            },
          },
          {
            label: "运行应采取的安全措施",
            prop: "safetyMeasures",
            type: "textarea",
            span: 24,
            autosize: true,
            maxlength: 3000,
            trigger: "change",
            isHide: true,
            placeholder: "请输入",
          },
          {
            label: "检修应采取的安全措施",
            prop: "safetyMeasuresRepair",
            type: "textarea",
            span: 24,
            maxlength: 3000,
            autosize: true,
            trigger: "change",
            isHide: true,
            placeholder: "请输入",
          },
        ],
      },
      // 基本信息表单数据
      basicFormData: {},
    };
  },
  computed: {
    // 操作按钮
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "icon-baocun",
          disabled: !this.$store.getters.isBtnAuth("save"),
          content: "未授权的功能",
          hide: false,
          methods: () => {
            if (this.title) {
              this.save();
            } else {
              this.$message.warning("标题不能为空");
              this.editTitle();
            }
          },
        },
        {
          text: "删除",
          icon: "icon-shanchu",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          content: "未授权的功能",
          hide: this.basicFormData.id ? false : true,
          methods: () => {
            this.delete();
          },
        },
      ];
      return arr;
    },
    // 更多按钮
    moreBtnArr() {
      let arr = [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ];
      return arr;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    // 初始化信息
    async init() {
      this.pageType = this.$route.query.pageType;
      let val = this.$route.query.val;
      if (this.pageType == "details") {
        // 详情
        this.basicFormData.id = val;
        this.getDetails(val);
        this.showMore = true;
        setInterval(() => {
          this.isEditInfo = true;
        }, 100);
      } else if (this.pageType == "add") {
        // 新增
        this.isEditInfo = true;
        this.ticketType = val;
        this.setFormItemShow(this.ticketType);
        this.showInput = true;
      } else if (this.pageType == "historyImport") {
        // 历史导入
        this.isEditInfo = true;
        this.setHistoryData(val);
      }
    },
    // 根据工作票类型设置表单显示及安全措施项
    async setFormItemShow(ticketType) {
      let types = this.$store.getters["dirtData"]("ticket_work_type");
      let obj = types.find((i) => i.value == ticketType);
      this.basicFormData.type$ = obj ? obj.label : ticketType;
      this.basicConfig.itemArr[1].isHide = false;
      this.basicConfig.itemArr[2].isHide = false;
      let type = { ticketType: this.ticketType };
      let { data } = await queryList(type);
      this.$set(this.safeDetails, "data", data); // 安全措施
    },
    // 设置历史导入数据
    async setHistoryData(id) {
      let res = await getWorkTicketInfo({ id });
      this.safeDetails.data = res.data.securityArrangementList
        ? res.data.securityArrangementList
        : [];
      this.ticketType = res.data.type ? res.data.type : "";
      this.setFormItemShow(this.ticketType);
      this.title = res.data.title ? res.data.title : "";
      this.basicFormData = Object.assign({}, this.basicFormData, {
        content: res.data.content ? res.data.content : "",
        safetyMeasures: res.data.workInfo
          ? res.data.workInfo.safetyMeasures
          : "",
        safetyMeasuresRepair: res.data.workInfo
          ? res.data.workInfo.safetyMeasuresRepair
          : "",
      });
      if (this.ticketType == "PowerLineFirst") {
        this.mergeType(this.safeDetails.data);
      }
    },
    //根据样票id获取详情信息
    async getDetails(id) {
      let { data } = await getSampleTicketData({ id: id });
      this.creatInfo = data;
      this.safeDetails.data = data.securityArrangementList
        ? data.securityArrangementList
        : [];
      this.ticketType = data.type;
      this.setFormItemShow(this.ticketType);
      this.title = data.title || "";
      this.basicFormData = Object.assign({}, this.basicFormData, {
        id: data.id,
        workInfoId: data.workInfo ? data.workInfo.id : "",
        content: data.content ? data.content : "",
        safetyMeasures: data.workInfo ? data.workInfo.safetyMeasures : "",
        safetyMeasuresRepair: data.workInfo
          ? data.workInfo.safetyMeasuresRepair
          : "",
      });
      if (this.ticketType == "PowerLineFirst") {
        this.mergeType(this.safeDetails.data);
      }
    },
    mergeType(data) {
      if (data.length > 0) {
        let indexList = [0];
        let sum = 0;
        let sumList = [];
        let sameName = data[0].type;
        for (let i = 0; i < data.length; i++) {
          if (sameName == data[i].type) {
            sum = sum + 1;
            if (data.length - 1 == i) {
              sumList.push(sum);
            }
          } else {
            sameName = data[i].type;
            indexList.push(i);
            sumList.push(sum);
            sum = 0;
            i--;
          }
        }
        for (let i = 0; i < indexList.length; i++) {
          data[indexList[i]].mergeLength = sumList[i];
          data[indexList[i]].action = "删除";
        }
      }
    },
    // 编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    // 编辑标题失去焦点判断内容
    loseFocus() {
      this.showInput = false;
    },
    // 添加填写表格数据
    addSafeItem() {
      if (this.safeConfig.length > 0) {
        let arr = this.copyArr(this.safeConfig);
        arr.forEach((item, index) => {
          if (index == 0) {
            item.mergeLength = this.safeConfig.length;
          }
          item.sort += this.safeDetails.data.length;
        });
        this.safeDetails.data = [...this.safeDetails.data, ...arr];
      } else {
        this.$message.warning(
          "业务配置管理未配置安全措施项，请先配置安全措施项。"
        );
      }
    },
    // 删除填写表格数据
    deleteSafeItem(data) {
      let index = this.safeDetails.data.findIndex((item) => {
        return item.sort == data.sort;
      });
      if (index == 0) {
        this.safeDetails.data.splice(
          0,
          this.safeDetails.data[index].mergeLength
        );
      } else {
        this.safeDetails.data.splice(
          index - 1,
          this.safeDetails.data[index].mergeLength
        );
      }
    },
    // 合并表格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并列下标对应columnIndex 以及 返回数组的第二个参数
      if (columnIndex === 0 || columnIndex === 3) {
        if (row.mergeLength) {
          // 如果有值,说明需要合并
          return [row.mergeLength, 1];
        } else {
          return [0, 0];
        }
      }
    },
    copyArr(arr) {
      let newArr = [];
      for (let i in arr) {
        newArr[i] = Object.assign({}, arr[i]);
      }
      return newArr;
    },
    // 保存
    async save() {
      let data = await this.$refs.basicForm.getFormData();
      let workTicket = {
        content: data.content,
        id: data.id,
        type: this.ticketType,
        title: this.title,
      };
      let workInfo = {
        workInfo: {
          fakeTicketId: data.id,
          id: data.workInfoId,
          safetyMeasures: data.safetyMeasures,
          safetyMeasuresRepair: data.safetyMeasuresRepair,
        },
      };
      let dataList = workTicket;
      dataList = Object.assign(workInfo, dataList);
      await saveSampleTicket(dataList).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.description);
          this.updateListData();
          if (this.pageType == "add" || this.pageType == "historyImport") {
            let obj = {
              val: res.data,
              pageType: "details",
            };
            this.$router.push({
              query: obj,
            });
            this.$utils.addOperateLog(
              res.data,
              `新建了${this.basicFormData.type$}样票`
            );
          } else {
            this.$utils.addOperateLog(
              res.data,
              `修改了${this.basicFormData.type$}样票`
            );
          }
          this.getDetails(res.data);
        }
      });
    },
    // 删除
    async delete() {
      let val = { id: this.basicFormData.id ? this.basicFormData.id : "" };
      if (val.id) {
        this.$confirm(`是否确认删除`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            deleteSampleTicket(val).then(async (res) => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.updateListData();
                setTimeout(() => {
                  window.close();
                }, 1000);
              }
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("当前样票没有保存");
      }
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  background-color: #ffffff;
  .title {
    font-size: 14px;
    font-weight: 500;
    color: #000;
    background: #f2f2f2;
    padding: 4px 10px;
    border-radius: 14px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
  .info-data {
    width: 80%;
    margin: 0 auto;
  }
  .table-content {
    position: relative;
    z-index: 1;
    .itemTitle {
      padding: 0 12px 0 0;
      height: 40px;
      line-height: 40px;
      text-align: right;
      vertical-align: middle;
      text-overflow: ellipsis;
      font-size: 14px;
      color: #606266;
    }
    .safe-info {
      position: relative;
      .add-btn {
        float: left;
        margin: 10px 0;
      }
      .safe-data {
        margin: 0 0 30px 0;
        /deep/ th > .cell {
          text-align: center;
        }
        /deep/ .cell {
          text-align: center;
        }
        /deep/ .el-form-item__error {
          position: relative;
        }
        .line-info {
          margin: 0 auto;
          font-size: 14px;
          color: #606266;
          .el-input {
            width: 80%;
            margin: 10px;
          }
        }
      }
    }
    .line-table {
      /deep/ .el-table__header-wrapper {
        display: none;
      }
      /deep/ .line-value {
        color: #666;
        font-weight: 600;
      }
    }
  }
}
</style>